import React from 'react';
import { GetServerSideProps } from 'next';
import AuthLayout from '../../src/components/layout/AuthLayout';
import Splash from '../../src/components/pages/auth/Splash';
import SignUp from '../../src/components/pages/auth/SignUp';
import { SignUpProps } from '../../src/model/components/signUp';
import getDepartments from '../../src/utils/api/getDepartments';
import getTeams from '../../src/utils/api/getTeams';
import getCustomSettings from '../../src/utils/api/getSettings';
import SignUpClosed from '../../src/components/pages/auth/SignUpClosed';

const showSplash = false;
const showSignUp = true;

const signUp: React.FC<SignUpProps> = ({
  departments,
  teams,
  selectedTeam,
  registerOpen,
}) => (
  <AuthLayout
    title="Nuevo usuario"
    mainClassName={showSplash || !registerOpen ? 'splash' : 'signUp'}
    splash={showSplash || !registerOpen}
    auth
  >
    {registerOpen ? (
      <>
        {showSplash ? <Splash /> : null}
        {showSignUp && !showSplash ? (
          <SignUp
            departments={departments}
            teams={teams}
            selectedTeam={selectedTeam}
          />
        ) : null}
      </>
    ) : (
      <SignUpClosed />
    )}
  </AuthLayout>
);

export const getServerSideProps: GetServerSideProps<SignUpProps> = async (
  ctx,
) => {
  const { token } = ctx.params;

  const departments = await getDepartments();
  const teams = await getTeams();
  const customSettings = await getCustomSettings();

  const selectedTeam =
    !!token && !!teams ? teams.find((team) => team.id === token) : null;

  if (!selectedTeam) {
    return {
      redirect: {
        destination: `/signUp`,
        permanent: true,
      },
    };
  }

  return {
    props: {
      departments,
      teams,
      selectedTeam,
      registerOpen: customSettings?.registerOpen,
    },
  };
};

export default signUp;
